from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Optional

mcp = FastMCP("Tog-Pegasus MCP Server")

"""
面向软件：tog-pegasus
所有 MCP tool 列表：

1. tog_pegasus_service_control
   - 用途：控制 tog-pegasus 服务的状态（启动、停止、重启、重载等）
   - 参数：action (str) - 服务操作类型：start|stop|restart|reload|status
   - 返回结构：统一JSON格式，包含success, command, exit_code, stdout, stderr
"""

@mcp.tool()
def tog_pegasus_service_control(action: str) -> dict:
    """
    控制 tog-pegasus 服务的状态
    
    参数:
        action: 服务操作类型，可选值：start, stop, restart, reload, status
    
    返回:
        JSON结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    valid_actions = ['start', 'stop', 'restart', 'reload', 'status']
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} tog-pegasus.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Must be one of {valid_actions}"
        }
    
    cmd = ["systemctl", action, "tog-pegasus.service"]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()